package com.snail.starter.cloud.i18n;

import com.snail.starter.commons.threadlocal.UserContext;
import com.snail.starter.commons.threadlocal.UserContextUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * @author: snail framework
 * @Date: 2023/2/21 上午9:53
 * @Version: 1.0.0
 */
public class I18nInterceptor extends LocaleChangeInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
        String locale = request.getHeader(getParamName());
        if (null == locale) {
            return true;
        }
        if (!checkMethod(request.getMethod())) {
            return true;
        }
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        if (localeResolver == null) {
            throw new IllegalStateException(
                    "No LocaleResolver found: not in a DispatcherServlet request?");
        }
        try {
            Locale localeBean = parseLocaleValue(locale);
            localeResolver.setLocale(request, response, localeBean);
            if(null != localeBean){
                UserContext userContext = UserContextUtils.get();
                userContext.setLocale(localeBean.toString());
                UserContextUtils.set(userContext);
            }
        } catch (IllegalArgumentException ex) {
            if (!isIgnoreInvalidLocale()) {
                throw ex;
            }
            logger.warn("Ignoring invalid locale value [" + locale + "]: " + ex.getMessage());
        }
        return true;
    }

    private boolean checkMethod(String currentMethod) {
        String[] configuredMethods = getHttpMethods();
        if (ObjectUtils.isEmpty(configuredMethods)) {
            return true;
        }
        for (String configuredMethod : configuredMethods) {
            if (configuredMethod.equalsIgnoreCase(currentMethod)) {
                return true;
            }
        }
        return false;
    }
}
